package com.gopay.cron.service.trans.impl;

import com.gopay.common.constants.cust.UserSourceConstans;
import com.gopay.cron.service.trans.ExportExcelService;
import com.gopay.cron.web.util.DicTranslate;
import com.gopay.scheduler.GopayBaseJob;
import com.gopay.scheduler.job.vo.OptimizedTransQueryVO;
import com.gopay.scheduler.service.AutoGenTrade.AutoGenTradeService;
import com.gopay.scheduler.util.DateUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service(value = "exportExcelService")
public class ExportExcelServiceImp extends GopayBaseJob implements ExportExcelService {
	public static final int PAGE_SIZE = 500;
	// 日志
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Resource(name = "autoGenTradeService")
	private AutoGenTradeService autoGenTradeService;
	private @Value("#{webProperties['transDownload_beginDate']}") String start;
	private @Value("#{webProperties['transDownload_endDate']}") String end;
	private @Value("#{webProperties['transDownload_isHistory']}") String isHistory;
	private @Value("#{webProperties['transDownload_downPath']}") String downPath;
	private @Value("#{webProperties['transDownload_retentionTime']}") String retentionTime;
	@Override
	public boolean exportExcel(String beginDate,String endDate){
		boolean result = true;
		try {
			// 先判断目录存不存在，目录定在usr/local/ciecc/newtrans目录下
			// String path="usr/local/ciecc/newtrans";
			File file = new File(downPath);
			if (!file.exists()) {
				file.mkdirs();
			}

			String today =DateUtils.convertStringDateToStringDate("yyyyMMdd", "yyyy-MM-dd", beginDate);
			OutputStream os = new FileOutputStream(downPath + today
					+ "成功交易记录.xlsx");
			/**
			 * rowAccessWindowSize代表指定的内存中缓存记录数，默认为100，此值可以通过 new
			 * SXSSFWorkbook(int rowAccessWindowSize)
			 * 比如内存中限制行数为100，当行号到达101时，行号为0的记录刷新到硬盘并从内存中删除，
			 * 当行号到达102时，行号为1的记录刷新到硬盘，并从内存中删除，以此类推。
			 */

			SXSSFWorkbook wb = new SXSSFWorkbook(100);
			SXSSFSheet sheet =(SXSSFSheet)  buildTitleCells(wb);
			// 查询
			int pageIndex = 1;
			int count = autoGenTradeService.getDataCount(beginDate,endDate);
			int i = (int) Math.ceil(count*1.0 / PAGE_SIZE);
//			logger.info("----------count="+count+"-------------i="+i);

			int rownum=1;
			while (i>=pageIndex){
				List<OptimizedTransQueryVO> orderList = autoGenTradeService.getDataList(beginDate,endDate,pageIndex, PAGE_SIZE);
				rownum = buildContentCells(sheet, orderList, rownum);
				pageIndex+=1;
				sheet.flushRows();
			}
			wb.write(os);
			os.close();
			logger.info("----------成功了-----------");
		} catch (Exception e) {
			logger.error("trade down load program generate file error :" + e);
			e.printStackTrace();
			result = false;
		}
		return result;
	}

	protected Sheet buildTitleCells(SXSSFWorkbook workbook) {
		// 表单名称
		String sheetName = getSheetName();
		// 标题名称
		String[] titles = getTitles();
		// 列宽
		short[] colWidths = getColumnWidths();

		// 创建表格
		Sheet sheet = workbook.createSheet(sheetName);

		// 字体
		Font font = workbook.createFont();
		font.setFontName(HSSFFont.FONT_ARIAL);
		font.setFontHeightInPoints((short) 10);
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		font.setColor(HSSFColor.BLACK.index);

		// 标题单元格样式
		CellStyle titleStyle = workbook.createCellStyle();
		titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		titleStyle.setFont(font);

		// 默认内容单元格样式
		CellStyle contentStyle = workbook.createCellStyle();
		contentStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

		// 标题行
		Row titleRow = sheet.createRow(0);

		// 创建标题行单元格
		for (int i = 0; i < titles.length; i++) {
			// 标题单元格
			Cell cell = titleRow.createCell((short) i);
			cell.setCellType(Cell.CELL_TYPE_STRING);
			cell.setCellValue(new XSSFRichTextString(titles[i]));
			cell.setCellStyle(titleStyle);

			// 设置列宽
			sheet.setColumnWidth((short) i, (short) (colWidths[i] * 256));
			// 设置列默认样式
			sheet.setDefaultColumnStyle((short) i, contentStyle);
		}

		return sheet;
	}

	protected int buildContentCells(Sheet sheet,
			List<OptimizedTransQueryVO> list,int count) {
		int i = 0;
		for (OptimizedTransQueryVO r : list) {
			// 创建内容单元格
			Row crow = sheet.createRow(count++);
			i = 0;
			crow.createCell((short) i++).setCellValue(
					new XSSFRichTextString(r.getGopayTxnTmBegin()));
			crow.createCell((short) i++).setCellValue(
					new XSSFRichTextString(r.getOrderStlmTmBegin()));
			crow.createCell((short) i++).setCellValue(
					new XSSFRichTextString(r.getCustOrderId()));
			crow.createCell((short) i++).setCellValue(
					new XSSFRichTextString(r.getGopayOrderId()));
			crow.createCell((short) i++).setCellValue(
					new XSSFRichTextString(r.getTxnPlace()));
			crow.createCell((short) i++).setCellValue(
					new XSSFRichTextString(r.getPayCustName()));
			//金额修改-增加结算金额字段-jiaoshuai》update by jiaoshuai 20160815隐藏掉结算金额
			//modify by leixiaobao 2016-08-30 增加结算金额
			crow.createCell((short) i++).setCellValue(
			        new XSSFRichTextString(r.getTotalOrderAmt().toString()));
			crow.createCell((short) i++).setCellValue(
			        new XSSFRichTextString(r.getSettleAmt().toString()));
			crow.createCell((short) i++).setCellValue(
					new XSSFRichTextString(r.getTxnAmt().toString()));
			crow.createCell((short) i++).setCellValue(
					new XSSFRichTextString(r.getRealFeeAmt().toString()));
			//金额修改-增加手续费承担方字段-jiaoshuai
            crow.createCell((short) i++).setCellValue(
                    new XSSFRichTextString(r.getOrderFeePayer()));
			crow.createCell((short) i++).setCellValue(
					new XSSFRichTextString(r.getPayBankName()));
			crow.createCell((short) i++).setCellValue(
					new XSSFRichTextString(r.getRecvBankName()));
			crow.createCell((short) i++).setCellValue(
					new XSSFRichTextString(r.getRecvBankOrderId()));
			crow.createCell((short) i++).setCellValue(
					new XSSFRichTextString(r.getPayCustEmail()));
			crow.createCell((short) i++).setCellValue(
					new XSSFRichTextString(r.getPayAcct()));
			crow.createCell((short) i++).setCellValue(
					new XSSFRichTextString(r.getRecvCustName()));
			crow.createCell((short) i++).setCellValue(
					new XSSFRichTextString(r.getRecvCustEmail()));
			crow.createCell((short) i++).setCellValue(
					new XSSFRichTextString(r.getRecvAcct()));
			crow.createCell((short) i++).setCellValue(
					new XSSFRichTextString(r.getPayAcctProdCd()));
			crow.createCell((short) i++).setCellValue(
					new XSSFRichTextString(r.getTxnCdName()));
			crow.createCell((short) i++).setCellValue(
					new XSSFRichTextString(r.getPayChannel()));
			crow.createCell((short) i++).setCellValue(
					new XSSFRichTextString(r.getTxnSts()));
			crow.createCell((short) i++).setCellValue(
					new XSSFRichTextString(r.getSettleType()));
			crow.createCell((short) i++).setCellValue(
					new XSSFRichTextString(r.getTerminalSource()));
			if(StringUtils.isNotBlank(r.getUserSource())){
			crow.createCell((short) i++).setCellValue(
					new XSSFRichTextString(UserSourceConstans.getValue(r.getUserSource())));
			}else{
			crow.createCell((short) i++).setCellValue(
						new XSSFRichTextString(r.getUserSource()));	
			}
			crow.createCell((short) i++).setCellValue(
					new XSSFRichTextString(r.getHandleStaCd()));
			crow.createCell((short) i++).setCellValue(
					new XSSFRichTextString(r.getRemark()));
			crow.createCell((short) i++).setCellValue(
					new XSSFRichTextString(DicTranslate.getPayChannelName(r.getOldPayChannel())));
		}

		return count;
	}
	protected String getSheetName() {
		return "交易查询结果";
	}
	protected String[] getTitles() {
		return new String[] { "国付宝交易时间", "清算时间", "客户订单号", "国付宝交易号", "交易场所",
		        //金额修改-增加结算金额和手续费承担方字段,并去掉总金额字段-jiaoshuai》update by jiaoshuai 20160815隐藏掉结算金额
				//modify by leixiaobao 2016-08-30 增加结算金额
				//"付款客户名称", "交易总金额(元)","交易金额(元)", "手续费(元)", "付款银行名称", "收款银行名称", "收款银行订单号",
				"付款客户名称", "交易总金额(元)", "结算金额(元)","交易金额(元)", "手续费(元)","手续费承担方", "付款银行名称", "收款银行名称", "收款银行订单号",
				"付款客户Email", "付款客户账号", "收款客户名称", "收款客户Email", "收款方账号",
				"付款方账号类型", "交易类型", "支付渠道", "交易状态", "付款渠道", "支付来源", "客户来源",
				"处理状态", "备注","原支付渠道"};
	}
	protected short[] getColumnWidths() {
		return new short[] { 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,20,20,
				//金额修改—增加2列》update by jiaoshuai 20160815隐藏掉结算金额,隐藏一列
				//modify by leixiaobao 2016-08-30 增加结算金额
				20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,20,20};
	}
	@Override
	protected void doJobInternal() {
		try {
			//是否批量执行历史数据
			if("true".equals(isHistory)){
				 Date dBegin = null;
				 Date dEnd = null;
				 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				
				 try {
					 dBegin = sdf.parse(start);
					 dEnd = sdf.parse(end);
					 logger.error(dBegin+"时间"+dEnd);
					 List<Date> lDate = DateUtils.getDates(dBegin, dEnd);
					 for (Date date : lDate)
					 {
						 exportExcel(sdf.format(date),sdf.format(DateUtils.plusDays(date,1)));
						 
					 }
				 } catch (Exception e) {
					 e.printStackTrace();
					 logger.error("********执行生成文件错误********原因为："+e);
				 }
				
			}else{
				String delFileName=DateUtils.convertDateToStringDate("yyyyMMdd", DateUtils.plusDays(new Date(), Integer.valueOf(retentionTime)));
				//每天删除历史数据文件
				delHistoryFile(downPath+delFileName+"成功交易记录.xlsx");
				String today =DateUtils.formatDate(DateUtils.plusDays(new Date(), -1), "yyyy-MM-dd");
				String tomorrow =DateUtils.formatDate(new Date(), "yyyy-MM-dd");
				logger.info("我已经开始执行自动生成记录了");
				//生成文件
				exportExcel(today,tomorrow);
			}

			logger.info("AutoGenTradeRecord生成记录成功");
		} catch (Exception e) {
			logger.info("有错误了，错误信息如下:");
			e.printStackTrace();
		}
	}
	public boolean delHistoryFile(String path){
		File file = new File(path);
		boolean result= false;
		
		if(file.exists()){
			//删除历史文件
			result=file.delete();
		}
		return result;
	}
}
